<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>websocket多终端通讯</title>
</head>
<body>
    <ul id="content">

    </ul>
    <input type="text" id="msg">
    <button onclick="send()">发送</button>

    <script>
        const ws = new WebSocket('ws://localhost:3000')

        //监听建立连接
        ws.onopen = function (res) {
            console.log('连接成功')
        }

        //监听有新消息
        const ulContent = document.getElementById('content')
        ws.onmessage = msg => {
            const li = document.createElement('li')
            li.innerText = msg.data
            ulContent.appendChild(li)
        }

        //发送消息
        const inputNode = document.getElementById('msg')
        function send() {
            ws.send(inputNode.value)
        }
    </script>
</body>
</html>